package org.jeecg.modules.flow.callback.inbound.other;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.plant.entity.WmsSapWarehouseMap;
import org.jeecg.modules.basic.plant.mapper.WmsSapWarehouseMapMapper;
import org.jeecg.modules.basic.saplocation.entity.WmsSapLocation;
import org.jeecg.modules.basic.saplocation.service.IWmsSapLocationService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseMapper;
import org.jeecg.modules.business.doc.business.entity.WmsInReceiptMaterial;
import org.jeecg.modules.business.doc.business.service.IWmsInReceiptMaterialService;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskService;
import org.jeecg.modules.dock.entity.dto.request.InventoryAdjustRequestDTO;
import org.jeecg.modules.dock.entity.dto.response.InventoryUpdateResponseDTO;
import org.jeecg.modules.dock.service.SapDockingRepeaterService;
import org.jeecg.modules.flow.callback.enums.SimpleDocumentTypeEnum;
import org.jeecg.modules.flow.callback.enums.TransferStatusEnum;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.exception.FlowNoActionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 盘盈单sap过账
 *
 * @author lumingyi
 * @version 1.0.0
 * @since 2024-01-17
 */
@Component
@Slf4j
public class R32PassSAPBeforeBean<T> extends BaseCustomBeanRun<T> {
    @Autowired
    private IWmsInReceiptMaterialService inReceiptMaterialService;
    @Resource
    private WmsSapWarehouseMapMapper sapWarehouseMapMapper;
    @Resource
    private WmsBasicWarehouseMapper warehouseMapper;
    @Autowired
    private IWmsSapLocationService sapLocationService;
    @Autowired
    private SapDockingRepeaterService sapDockingRepeaterService;
    @Autowired
    private IBasicMaterialService basicMaterialService;
    @Autowired
    private IWmsInReceiptTaskService wmsInReceiptTaskService;

    @Override
    @Transactional(rollbackFor = FlowNoActionException.class)
    public void actureRun() {
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        String id = baseFlowDto.getInfoId();

        // 盘盈单sap过账
        List<InventoryAdjustRequestDTO> list = new ArrayList<>();
        List<WmsInReceiptMaterial> receiptMaterials = inReceiptMaterialService.selectByMainId(id);
        for (WmsInReceiptMaterial material : receiptMaterials) {
            InventoryAdjustRequestDTO dto = new InventoryAdjustRequestDTO();
            BasicMaterial byId = basicMaterialService.getById(material.getWmsBasicMaterialId());
            dto.setMaterialCode(byId.getCode());
            WmsSapWarehouseMap one = sapWarehouseMapMapper.selectOne(new LambdaQueryWrapper<WmsSapWarehouseMap>()
                    .eq(WmsSapWarehouseMap::getWmsBasicWarehouseId, material.getWmsBasicWarehouseId())
                    .last("limit 1"));
            if (one == null) {
                WmsBasicWarehouse warehouse = warehouseMapper.selectById(material.getWmsBasicWarehouseId());
                baseFlowDto.setResult("过账失败，仓库【" + warehouse.getName() + "】没有配置对应的sap库位");
                //更新过账状态 过账失败
                wmsInReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.IN_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
            }
            dto.setLocation(one.getSapLocation());
            WmsSapLocation sapLocation = sapLocationService.getOne(new LambdaQueryWrapper<WmsSapLocation>()
                    .eq(WmsSapLocation::getCode, one.getSapLocation())
                    .last("limit 1"));
            if (sapLocation == null) {
                WmsBasicWarehouse warehouse = warehouseMapper.selectById(material.getWmsBasicWarehouseId());
                baseFlowDto.setResult("过账失败，仓库【" + warehouse.getName() + "】没有配置对应的工厂");
                //更新过账状态 过账失败
                wmsInReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.IN_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
            }
            dto.setFactory(sapLocation.getFactory());
            dto.setSaleOrderCode(material.getSaleOrderNumber());
            dto.setSaleOrderCodeLine(material.getSaleOrderLineNumber());
            dto.setAdjustNumber(material.getReceivableQuantity());
            list.add(dto);
        }
        List<InventoryUpdateResponseDTO> dtos = new ArrayList<>();
        try {
            dtos = sapDockingRepeaterService.inventoryCountAdjustment(list);
        } catch (Exception e) {
            baseFlowDto.setResult(Result.error("盘盈单过账sap失败: "+e.getMessage()));
            //更新过账状态 过账失败
            wmsInReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.IN_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
        }
        if (CollectionUtil.isNotEmpty(dtos)) {
            InventoryUpdateResponseDTO res = dtos.get(0);
            if ("E".equals(res.getResult())) {
                baseFlowDto.setResult(Result.error("盘盈单过账sap失败: " + res.getMessage()));
                //更新过账状态 过账失败
                wmsInReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.IN_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
            }
        }

        baseFlowDto.setResult(Result.OK("操作成功"));
    }
}
